﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Repetition.Domain
{
    public class ProblemList
    {
        private IList<Problem> problems;
        private int selectedIndex;

        public ProblemList(IList<Problem> problems)
        {
            this.problems = problems;
        }

        public ProblemList(ICollection<Problem> problems)
        {
            this.problems = new List<Problem>();

            foreach (var p in problems)
                this.problems.Add(p);
        }

        public bool HasNext
        {
            get
            {
                ValidateIndex();
                return selectedIndex < problems.Count - 1;
            }
        }

        public bool HasPrevious
        {
            get
            {
                ValidateIndex();
                return selectedIndex > 0;
            }
        }

        public Problem CurrentProblem
        {
            get
            {
                ValidateIndex();
                return problems[selectedIndex];
            }
        }

        public int CurrentIndex
        {
            get
            {
                ValidateIndex();
                return selectedIndex;
            }
        }

        public int Count
        {
            get
            {
                return problems.Count;
            }
        }

        public void RemoveCurrent()
        {
            problems.Remove(CurrentProblem);

            if (problems.Count > 0 && selectedIndex > 0)
                selectedIndex--;
        }

        private void ValidateIndex()
        {
            ValidateIndex(selectedIndex);
        }

        private void ValidateIndex(int index)
        {
            if ((index >= problems.Count && problems.Count > 0) || index < 0)
                throw new IndexOutOfRangeException();
        }

        public void MoveNext()
        {
            ValidateIndex();

            if (HasNext)
                selectedIndex++;
        }

        public void MovePrevious()
        {
            ValidateIndex();

            if (HasPrevious)
                selectedIndex--;
        }

        public void SetCurrentIndex(int index)
        {
            ValidateIndex(index);
            selectedIndex = index;
        }
    }
}
